package com.magirard.project.manager.io
{
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	import flash.utils.ByteArray;
	
	public class InputManagerImpl
	{
		private const KEY_UP:int = 1;
		private const KEY_PRESSED:int = 2;
		private const KEY_DOWN:int = 3;
		private const KEY_RELEASED:int = 4;
		
		private var mStageRef:Stage;
		private var mKeyboardState:Vector.<int>;
		private var mKeyboardStateLastFrame:Vector.<int>;
		
		public function InputManagerImpl() 
		{
			
		}
		
		public function Init(aStageRef:Stage):void
		{
			mKeyboardStateLastFrame = new Vector.<int>(250);
			mKeyboardState = new Vector.<int>(250);
			mStageRef = aStageRef;
			mStageRef.addEventListener(KeyboardEvent.KEY_DOWN, OnKeyDown, false, 0, true);
			mStageRef.addEventListener(KeyboardEvent.KEY_UP, OnKeyUp, false, 0, true);
			mStageRef.addEventListener(Event.ENTER_FRAME, Update, false, 0, true);
		}
		
		private function Update(e:Event):void 
		{
			mKeyboardStateLastFrame = mKeyboardState.slice(0, mKeyboardState.length - 1);
		}
		
		private function OnKeyDown(aEvent:KeyboardEvent):void
		{
			if (aEvent.keyCode <= 250)
			{
				mKeyboardState[aEvent.keyCode] = 1;
			}
		}
		
		private function OnKeyUp(aEvent:KeyboardEvent):void 
		{
			if (aEvent.keyCode <= 250)
			{
				mKeyboardState[aEvent.keyCode] = 0;
			}
		}
		
		public function IsKeyDown(aKey:int):Boolean
		{
			return mKeyboardState[aKey] == 1;
		}
		
		public function IsKeyPressed(aKey:int):Boolean
		{
			return (mKeyboardState[aKey] == 1 && mKeyboardStateLastFrame[aKey] == 0);
		}
		
		public function IsKeyReleased(aKey:int):Boolean
		{
			return (mKeyboardState[aKey] == 0 && mKeyboardStateLastFrame[aKey] == 1);
		}
		
	}
}